package org.framework.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.framework.cache.CacheService;
import org.framework.session.SessionContext;

import com.hiwan.platform.util.BeanUtils;
import com.hiwan.platform.utils.StringUtils;

public class HiwanSessionListener implements HttpSessionListener,
		HttpSessionAttributeListener {
	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		if (StringUtils.equals("sessionUserId", se.getName())
				&& se.getValue() != null) {
			CacheService cacheService = BeanUtils.getBean("cacheService",
					CacheService.class);
			cacheService.put("sessionCache", (String) se.getValue(), se
					.getSession().getId());
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		if (StringUtils.equals("sessionUserId", se.getName())) {
			String userId = (String) se.getValue();
			String sessionId = se.getSession().getId();
			removeSessionCache(userId, sessionId);
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		String userId = SessionContext.getUserId(se.getSession());
		if (userId != null) {
			String sessionId = se.getSession().getId();
			removeSessionCache(userId, sessionId);
		}
	}

	private void removeSessionCache(String userId, String sessionId) {
		CacheService cacheService = BeanUtils.getBean("cacheService",
				CacheService.class);
		try {
			if (StringUtils.equals(sessionId,
					(String) cacheService.get("sessionCache", userId))) {
				cacheService.remove("sessionCache", userId);
			}
		} catch (NoSuchFieldException e) {
		}

	}
}
